package com.wr.online.test.handler;

import com.wr.online.test.exception.GlobalException;
import com.wr.online.test.model.vo.RespBean;
import com.wr.online.test.model.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author GZHU_WANG
 */
@ControllerAdvice
@ResponseBody
public class ExceptionController {


//    @ExceptionHandler(BindException.class)
//    public String bindException(Exception e) {
//        BindException be = (BindException) e;
//        System.out.println(Objects.requireNonNull(be.getBindingResult().getFieldError()).getDefaultMessage());
//        return be.getBindingResult().getFieldError().getDefaultMessage();
//    }
    //TemplateInputException
//    @ExceptionHandler(TemplateInputException.class)
//    public String templateInputException(Exception e) {
//        TemplateInputException be = (TemplateInputException) e;
//        System.out.println(Objects.requireNonNull(be.getLocalizedMessage()));
//        return be.getLocalizedMessage() + "找不到此页面";
//    }
    @ExceptionHandler(Exception.class)
    public RespBean exception(Exception e) {
        e.printStackTrace();
        if(e instanceof GlobalException){
            GlobalException e1 = (GlobalException) e;
            return RespBean.error(e1.getRespBeanEnum());
        }else if(e instanceof BindException){
            BindException e1 = (BindException) e;
            RespBean error = RespBean.error(RespBeanEnum.BIND_ERROR);
            error.setMessage(e1.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return error;
        }

        return RespBean.error(RespBeanEnum.ERROR);
    }


}